---
--类名: TeamGroup.lua
--创建日期: 2016-3-16
--创建人: 陈小虎
--功能描述: 桌面队伍组
--修改内容:
--修改日期:
--修改人:
--修改备注:
--

local AvatarIconNode = require("app.widget.AvatarIconNode")

local TeamGroup = class("TeamGroup")

function TeamGroup:ctor(groupRoot,functionRoot)
	cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()

	self._groupRoot = groupRoot
	self._functionRoot = functionRoot
	
	self:init()
end

function TeamGroup:init()
	local baseHeadNode = cc.uiloader:load(Res.BaseHeadMain)
	local headRoot = baseHeadNode:getChildByName("Panel")
	self._scaleRate = 1.0
	self._headWidth = headRoot:getContentSize().width * self._scaleRate
	self._memIcons = {}
	self:getMemberRoot():removeAllChildren()
	self._memberWidth = self:getMemberRoot():getContentSize().width

	self:updateFuncWidth()
end

function TeamGroup:updateFuncWidth()
	self._functionWidth = 0
	for i,v in ipairs(self._functionRoot:getChildren()) do
		if v:isVisible() then
			self._functionWidth = self._functionWidth + v:getContentSize().width
		end
	end
end

function TeamGroup:getMemberRoot()
	return self._groupRoot
end

function TeamGroup:getFunctionRoot()
	return self._functionRoot
end

function TeamGroup:setHeadNode(root,data, ui)
	if not ui then
		ui = display.uiDelegate(root)
	end
	local TeamModel = app:getInst("TeamModel")
	local panelRoot = ui["Panel"]
	local leadFlag = ui["Panel/icon_leader"]
	local avatarIconNode = AvatarIconNode.new(panelRoot, "icon", "mask")
	avatarIconNode:update(data)

	if TeamModel:isLeader(data.uid) then
		panelRoot:reorderChild(leadFlag,1)
		leadFlag:setVisible(true)
	else
		leadFlag:setVisible(false)
	end
end

function TeamGroup:refreshSingelHead(uid)
	local memberRoot = self:getMemberRoot()
	if not memberRoot then return end
	local mRoot = memberRoot:getChildByName(uid)
	if not mRoot then return end
	local baseInfo = FieldManager:getBaseInfoById(uid)
	if not baseInfo then return end
	baseInfo = clone(baseInfo)
	baseInfo.level = baseInfo.lv
	self:setHeadNode(mRoot,baseInfo)
end


function TeamGroup:resetMemIcon()
	self._curCacheIndex = 1
	for k, v in pairs(self._memIcons) do
		v[1]:setVisible(false)
	end
end

function TeamGroup:getMemIconFromCache()
	if self._curCacheIndex > #self._memIcons then
		local memberRoot = self:getMemberRoot()
		local mRoot = cc.uiloader:load(Res.BaseHeadMain)

		memberRoot:addChild(mRoot)
		local ui = display.uiDelegate(mRoot)
		table.insert(self._memIcons, {mRoot, ui})
		self._curCacheIndex = self._curCacheIndex + 1
		return mRoot, ui
	end
	local info = self._memIcons[self._curCacheIndex]
	self._curCacheIndex = self._curCacheIndex + 1
	return info[1], info[2]
end

-- TODO 可以优化 头像对象可以被缓存，不需要每次创建
function TeamGroup:refreshTeamGroup()
	local memberRoot = self:getMemberRoot()
	self:resetMemIcon()
	-- memberRoot:removeAllChildren()

	local team = app:sendMsg("TeamModel", "getTeam")
	if not team then return end

	local memberNum = team:getMemberNum()
	local maxNum = team:getMaxNumOfMembersByTeamGarde()

	-- 机器人
	local robotNum = team:getRobotNum()
	memberNum = memberNum + robotNum

	-- 随从
	local leaderPartners = team:getLeaderPartnerInfo()
	local leaderPartnersNum = #leaderPartners
	
	if maxNum > memberNum  then -- 存在空位 && 队长带有随从
		memberNum = memberNum + leaderPartnersNum -- 加一个位置给随从
		if memberNum > maxNum then
			memberNum = maxNum
		end
	end

	self:updateFuncWidth()

	memberRoot:setPosition(cc.p(self:getFunctionRoot():getPositionX() + self._functionWidth,memberRoot:getPositionY()))

	local interval = self._memberWidth / memberNum
	interval = (interval > self._headWidth) and self._headWidth or interval

	local x = 0
	local y = 0

	local members = team:getMembers()--team:getOtherMembers()
	local count = 1
	for k,member in pairs(members) do
		local memberUid = member.userBaseInfo.uid
		local mRoot, ui = self:getMemIconFromCache()
		mRoot:setScale(self._scaleRate)
		mRoot:setName(memberUid)
		x = (count - 1) * interval
		mRoot:setPosition(cc.p(x,y))
		local panelRoot = ui["Panel"]
		local menuPos = cc.p(panelRoot:getPositionX(),panelRoot:getPositionY() - panelRoot:getContentSize().height / 2)
		local menuPos = panelRoot:getParent():convertToWorldSpace(menuPos)
		panelRoot:addClickEventListener(function(sender)
			self:dispatchEvent({name = "onSwitchMemberPlayerMenu",pos = menuPos,member = member})
		end)
		mRoot:setVisible(true)
		local baseInfo = FieldManager:getBaseInfoById(memberUid)
		baseInfo = (baseInfo ~= nil) and clone(baseInfo) or clone(member.userBaseInfo)
		baseInfo.level = baseInfo.lv
		self:setHeadNode(mRoot,baseInfo, ui)
		count = count + 1
	end

	local robots = team:getRobots()
	for i,robot in ipairs(robots) do
		local mRoot,ui = self:getMemIconFromCache()
		mRoot:setVisible(true)
		mRoot:setScale(self._scaleRate)
		x = (count - 1) * interval
		mRoot:setPosition(cc.p(x,y))
		local panelRoot = ui["Panel"]
		local menuPos = cc.p(panelRoot:getPositionX(),panelRoot:getPositionY() - panelRoot:getContentSize().height / 2)
		local menuPos = panelRoot:getParent():convertToWorldSpace(menuPos)
		panelRoot:addClickEventListener(function(sender)
			self:dispatchEvent({name = "onSwitchMemberPlayerMenu",pos = menuPos,member = member})
		end)
		self:setHeadNode(mRoot,robot:getBaseInfo(), ui)
		count = count + 1
	end

	-- 填充队长随从
	for k, v in pairs(leaderPartners) do
		if maxNum < count  then
			break
		end
		local mRoot, ui = self:getMemIconFromCache()
		mRoot:setVisible(true)
		local panelRoot =ui["Panel"]
		local iconPath = v:getIcon()
		ui["Panel/icon"]:loadTexture( iconPath )
		ui["Panel/mask"]:setVisible( false )
		ui["Panel/icon_leader"]:setVisible( false )
		ui["Panel/icon_lx"]:setVisible( false )
		
		mRoot:setScale( self._scaleRate )
		x = ( count - 1 ) * interval
		mRoot:setPosition( cc.p( x, y ) )
		local menuPos = cc.p( panelRoot:getPositionX(), panelRoot:getPositionY() - panelRoot:getContentSize().height / 2 )
		local menuPos = panelRoot:getParent():convertToWorldSpace( menuPos )
		panelRoot:addClickEventListener( function( sender )
			self:dispatchEvent({name = "onSwitchMemberPlayerMenu",pos = menuPos,member = member})
		end)
		count = count + 1
	end
end

return TeamGroup
